package dao.impl;

import dao.MessagesDao;
import entity.Messages;
import entity.vo.MessageData;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import utils.DruidUtils;

import java.sql.Connection;
import java.util.List;

public class MessagesDaoImpl implements MessagesDao {
    //TODO:默认每页查询10条数据
    private static final int PAGE_SIZE = 10;


    @Override
    public List<MessageData> selectPublicMessagePage(Integer pageNumber) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "select m.id, m.message, m.created_at, u.name\n" +
                    "from messages m join users u\n" +
                    "on m.user_id = u.id\n" +
                    "where power=1\n" +
                    "ORDER By created_at DESC\n" +
                    "limit ?, ?";
            QueryRunner queryRunner = new QueryRunner();
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            List<MessageData> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(MessageData.class, basicRowProcessor), (pageNumber - 1) * PAGE_SIZE, PAGE_SIZE);
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public List<MessageData> selectPrivateMessagePage() {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "select m.id, m.message, m.created_at, u.name\n" +
                    "from messages m join users u\n" +
                    "on m.user_id = u.id\n" +
                    "where power=0\n" +
                    "ORDER By created_at DESC ";
            QueryRunner queryRunner = new QueryRunner();
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            List<MessageData> query = queryRunner.query(conn, s,
                    new BeanListHandler<>(MessageData.class, basicRowProcessor));
            DruidUtils.close(null, conn);
            return query;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    /*常见处理器:
    ResultSetHandler<T>：用于将查询结果集中的行转换成对象 T，例如 BeanHandler<T>、BeanListHandler<T> 等。
    ScalarHandler<T>：用于处理单个结果值，例如单个值的查询结果。
    ArrayHandler：用于将查询结果集中的第一行转换成对象数组。
    ArrayListHandler：用于将查询结果集转换成对象数组列表。*/
    @Override
    public Integer getAllPage() {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "SELECT COUNT(*) AS count FROM messages where power=1";    //只要公开的留言
            QueryRunner queryRunner = new QueryRunner();
            //这个SELECT COUNT(*)查出来是Long形
            Long row = queryRunner.query(conn, s, new ScalarHandler<Long>());
            int totalPages = (int) Math.ceil((double) row / PAGE_SIZE);            // 计算总页数
            DruidUtils.close(null, conn);
            return totalPages;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return null;
    }

    @Override
    public boolean insertMessage(Messages messages) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "insert into messages (user_id, message, created_at, power) values (?,?,?,?)";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s, messages.getUserId(), messages.getMessage()
                    , messages.getCreatedAt(), messages.getPower());
            DruidUtils.close(null, conn);
            if (update > 0) return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return false;
    }


    @Override
    public Messages queryById(Integer id) {
        return null;
    }

    @Override
    public int update(Messages messages) {
        return 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String s = "delete from messages where id=?";
            QueryRunner queryRunner = new QueryRunner();
            int update = queryRunner.update(conn, s, id);
            DruidUtils.close(null, conn);
            if (update > 0) return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            DruidUtils.close(null, conn);
        }
        return false;
    }
}
